package com.ddwanglife.base

object GrammarDemo {
  def main(args: Array[String]): Unit = {
    var str = "Hello world";
    println(str)

    val i = 5
    val j = 8
    printf("My name is %s. I hava %d apples and %d eggs.\n", "Ziyu", i, j)

//    Java不同的是，Scala中的if表达式的值可以赋值给变量
    val x = 6
    val a = if (x>0) 1 else -1

    /*
    //for (变量<-表达式) 语句块
    for (i <- 1 to 5) println(i)
    for (i <- 1 to 5 by 2) println(i)
    for (i <- 1 to 5 if i%2==0) println(i)
    //类似嵌套循环
    for (i <- 1 to 5; j <- 1 to 3) println(i*j)
    //为嵌套循环增加判断条件
    for (i <- 1 to 5 if i%2==0; j <- 1 to 3 if j!=i) println(i*j)
    for (i <- 1 to 5 if i%2==0) yield i*/


//      数组
//    val intValueArr = new Array[Int](3)
//    intValueArr(0) = 1
//    val intValueArr = Array(12,"你好",33) //编译执行都没问题

    val intList = List(1,2,3)
    val intListOther = 0::intList //intListOther是一个新的列表List(0,1,2,3)

    val intList1 = List(1,2)
    val intList2 = List(3,4)
    val intList3 = intList1:::intList2

    val tuple = ("BigData",2015,45.0)

    var myMutableSet = Set("Database","BigData")
    myMutableSet += "Cloud Computing"
    println(myMutableSet)

    val university = Map("XMU" -> "Xiamen University", "THU" -> "Tsinghua University","PKU"->"Peking University")
    for ((k,v) <- university) printf("Code is : %s and name is: %s\n",k,v)

    val iter = Iterator("Hadoop","Spark","Scala")
    for (elem <- iter) println(elem)


//    模式匹配
    val colorNum = 1
    val colorStr = colorNum match {
      case 1 => "red"
      case 2 => "green"
      case 3 => "yellow"
      case _ => "Not Allowed"
    }
    println(colorStr)

    val numList = List(-3, -5, 1, 6, 9)
    numList.filter(x => x > 0 )
    numList.filter(_> 0)

  }
  //定义了一个新的函数sum，以函数f为参数
  def sum(f: Int => Int, a: Int, b: Int): Int ={
    if(a > b) 0 else f(a) + sum(f, a+1, b)
  }
  //定义了一个新的函数self，该函数的输入是一个整数x，然后直接输出x自身
  def self(x: Int): Int = x
  //重新定义sumInts函数
  def sumInts(a: Int, b: Int): Int = sum(self, a, b)
}
